<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <PageTools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共 19 条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button type="danger" size="small" @click="pushexcel"
            >导入excel</el-button
          >
          <el-button type="success" size="small" @click="exportExcel"
            >导出excel</el-button
          >
          <el-button type="primary" size="small" @click="addEmpShowDialogFn"
            >新增员工</el-button
          >
        </template>
      </PageTools>

      <el-card style="margin-top: 10px">
        <el-table border :data="employeesList">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template slot-scope="scope">
              <span class="title-img">
                <!-- <img
                  :src="scope.row.staffPhoto"
                  style="width: 40px; height: 40px"
                /> -->
                <imgeHolder  :src="scope.row.staffPhoto"
                  style="width: 40px; height: 40px"/>
              </span>
            </template>
          </el-table-column>

          <el-table-column label="手机号" prop="mobile" />
          <el-table-column
            label="工号"
            prop="workNumber"
            sortable
            :sort-method="workNumberSortFn"
          />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template v-slot="scope">
              <!-- <span>{{hireType.find(item=>item.id==scope.row.formOfEmployment).value}}</span> -->
              <span>{{ formtter(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column
            label="入职时间"
            prop="timeOfEntry"
            :formatter="formatter"
          />
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button type="text" size="small" @click="lookdetail(scope.row.id,scope.row.formOfEmployment)">查看</el-button>
              <el-button type="text" size="small" @click='assbtn(scope.row)'>分配角色</el-button>
              <el-button type="text" size="small" @click="delEmp(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

      <!-- 新增用户弹窗 -->

      <el-dialog
        @close="addEmpDialogCloseFn"
        :close-on-click-modal="false"
        title="新增员工"
        :visible.sync="showDialog"
      >
        <empDialog
          ref="addEmpDialog"
          @addCancelfn="addCancelfn"
          @addSubmitfn="addSubmitfn"
          :treeData="treeData"
        />
      </el-dialog>

         <!-- 角色分配管理弹窗 -->
      <el-dialog 
      :visible.sync="assshowDialog"
      title="分配角色"
        :close-on-click-modal="false"
      >
       <AssignRoleDialog ref='assignRo'   @enter='enter' @cancleDialog='cancleDialog' :allrows='allrows'/>

      </el-dialog>



    </div>
  </div>
</template>

<script>
import {assignRolesAPI} from '../../api/employees'
import {getusephotoid} from '../../api/user'
import {getRolesAPI} from '../../api/setting'
import AssignRoleDialog from './components/assignRoleDialog.vue'
import {
  getEmployeeListAPI,
  addEmployeeAPI,
  delEmployeeAPI,
} from "../../api/employees";
import { getdepartment } from "../../api/department";
// 树形结构的转换方法
import { transTree } from "@/utils/index";
import dayjs from "dayjs";
import empDialog from "./components/empDialog.vue";
import { export_json_to_excel } from "../../vendor/Export2Excel";
export default {
  data() {
    return {
      //分配角色控制权限管理的显示和隐藏
      assshowDialog:false,
      query: {
        page: 1, //页码
        size: 10, //每页条数
      },
      employeesList: [], // 员工列表
      total: 0, //数据总条数
      // 聘用形式
      hireType: [
        {
          id: 1,
          value: "正式",
        },
        {
          id: 2,
          value: "非正式",
        },
      ],
      showDialog: false, // 添加员工组件的展示
      treeData: [], // 存储部门列表(树结构)
      allrows:[], // 所有的角色对象
      clickEmpid:'' //员工的id
    };
  },
  components: { empDialog ,AssignRoleDialog},
  created() {
    this.getEmployeeListAPIFn();
    this.getDepartments();
    //获取所有角色列表数据
    this.getRolesAPIfn()
  },
  methods: {
    //导出表格
    exportExcel() {
      var tHeader = [
        "序号",
        "id",
        "姓名",
        "头像",
        "手机号",
        "工号",
        "聘用形式",
        "入职时间",
        "转正时间",
        "密码",
        "部门",
      ];
      var filterVal = [
        "序号",
        "id",
        "username",
        "staffPhoto",
        "mobile",
        "workNumber",
        "formOfEmployment",
        "timeOfEntry",
        "correctionTime",
        "password",
        "departmentName",
      ];
      var filename = "表格名称";
      // var newarr=this.employeesList(obj=>{
      //      return Object.values(obj)
      // })
      // filterVal.unshift(`${add}`)
      // let add=[];
      // console.log(add);
      // console.log(filterVal);
      // this.employeesList.forEach((item,index)=>{
      //   add.push(index + 1)
      // })
      this.employeesList.forEach((item, index) => {
        item["序号"] = index + 1;
        if (item.formOfEmployment == 1) {
          item.formOfEmployment = "正式";
        }
      });
      var data = this.formatJson(filterVal, this.employeesList);
      // var data = newarr

      export_json_to_excel({
        header: tHeader,
        data,
        filename,
      });
      this.getEmployeeListAPIFn();
    },
    formatJson(filterVal, tableData) {
      return tableData.map((v) => {
        return filterVal.map((j) => {
          return v[j];
        });
      });
    },

    //-----------------------------------------------------------------------------

    //获取属树形结构列表
    async getDepartments() {
      const res = await getdepartment();
      this.treeData = transTree(res.data.data.depts, "");
      // console.log(this.treeData);
    },
    //请求部门列表
    async getRolesAPIfn(){
      const res=await getRolesAPI({
        page:1,
        pagesize:10
      })
       const ress=await getRolesAPI({
          page:1,
        pagesize:res.data.data.total
       })
      //  console.log(ress);
      this.allrows=res.data.data.rows
      // console.log( this.allrows);
    },
    //获取员工信息
    async getEmployeeListAPIFn() {
      const res = await getEmployeeListAPI(this.query);
      // console.log(res);
      this.employeesList = res.data.data.rows;
      this.total = res.data.data.total;
     // console.log(this.employeesList);
    },

    //每页条数发生改变是触发
    handleSizeChange(size) {
      this.query.size = size;
      this.getEmployeeListAPIFn();
      // console.log(size);
    },
    //当前页面发生改变是触发
    handleCurrentChange(page) {
      this.query.page = page;
      this.getEmployeeListAPIFn();
      //  console.log(page);
    },

    formtter(row) {
      const obj = this.hireType.find((item) => item.id == row.formOfEmployment);
      return obj ? obj.value : "未知";
    },
    //自定义排序
    workNumberSortFn(a, b) {
      return Number(a.workNumber) - Number(b.workNumber);
    },
    //时间格式化
    formatter(row) {
      return dayjs(row.timeOfEntry, "YYYY-MM-DD").format("YYYY-MM-DD");
    },
    //点击新增员工按钮, 绑定事件方法, 为了让弹窗出现
    addEmpShowDialogFn() {
      this.showDialog = true;
    },
    //弹窗点击子组件取消按钮
    addCancelfn() {
      this.showDialog = false;
    },
    //弹窗点击子组件确定按钮
    async addSubmitfn(empobj) {
      const res = await addEmployeeAPI(empobj);
      // console.log(res);
      //  console.log(empobj);
      this.getEmployeeListAPIFn();
      this.showDialog = false;
    },
    //关闭弹窗后清除弹出框里的内容,
    addEmpDialogCloseFn() {
      this.$refs.addEmpDialog.$refs.addForm.resetFields();
    },
    //删除按钮
    delEmp(id) {
      const ress = this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delEmployeeAPI(id).then((res) => {
            // console.log(res);
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            if (this.employeesList.length == 1) {
              this.query.page--;
              // 如果是第一页的第一条
              if (this.query.page === 0) {
                this.query.page = 1;
              }
            }
            this.getEmployeeListAPIFn();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });

      // const res= await delEmployeeAPI(id)
    },
    //跳转到excel
    pushexcel() {
      this.$router.push("/excel");
    },
    //查看按钮跳转到详情页
    lookdetail(lookid,formOfEmployment){
      this.$router.push(`/employees/detail?id=${lookid}&formOfEmployment=${formOfEmployment}`)
    },
    //分配角色的按钮显示和隐藏
   async assbtn(objrow){
     this.clickEmpid=objrow.id
   this.assshowDialog=true
       const res= await getusephotoid(objrow.id)
      //  console.log(res);
      this.$nextTick(()=>{
 this.$refs.assignRo.roleIdslist= res.data.data.roleIds
      })
       
    },
    //弹出框里的确定按钮
   async enter(roleIdslist){
         const res=await assignRolesAPI({
           roleIds:roleIdslist,
           id:this.clickEmpid
         })


       this.assshowDialog =false
    },
    //弹出框取消
    cancleDialog(){
 this.assshowDialog=false
    }
    },
};
</script>

<style lang="scss" scoped>
</style>